package hs.bank.Web.Service;

import hs.bank.Data.CardMapper;
import hs.bank.Data.UserMapper;
import hs.bank.Web.Form.DepositForm;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.net.CacheRequest;

@Controller
@RequestMapping("/deposit")
public class DepositController {
    private UserMapper userMapper;
    private CardMapper cardMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setCardMapper(CardMapper cardMapper) {
        this.cardMapper = cardMapper;
    }

    @GetMapping("{cardNumber}")
    public String showForm(@PathVariable String cardNumber, Model model) {
        model.addAttribute("depositForm", new DepositForm());
        model.addAttribute("cardNumber", cardNumber);
        return "deposit";
    }

    @PostMapping("{cardNumber}")
    public String deposit(@PathVariable String cardNumber,
                          @Valid DepositForm depositForm,
                          BindingResult bindingResult,
                          Model model) {
        if (bindingResult.hasErrors()) {
            return "deposit";
        }
        try {
            double amount = depositForm.getAmount();
            cardMapper.deposit(amount, Integer.parseInt(cardNumber));
            return "redirect:/home";
        } catch (Exception e) {
            model.addAttribute("error", true);
        }
        return "deposit";
    }
}
